import logging
import  colorlog
import datetime
from logging import handlers
import os
from configs.path_conf import path_config

__all__ = ['log']

class Logger:

    @staticmethod
    def get_colorlog_formatter() -> colorlog.ColoredFormatter:
        return colorlog.ColoredFormatter(
            "%(log_color)s%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
            reset=True,
            log_colors={
                "DEBUG": "cyan",
                "INFO": "green",
                "WARNING": "yellow",
                "ERROR": "red",
                "CRITICAL": "red,bg_white"
            }
        )


    @staticmethod
    def getLogger(name_log) -> logging.Logger:
        # 获取log记录器
        logger = logging.getLogger(name_log)
        logger.setLevel(logging.DEBUG)

        #格式器
        formatter = logging.Formatter('%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s')

        # 日志输出到控制台
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(Logger.get_colorlog_formatter())

        # 日志记录到文件中
        log_dir = path_config.log_dir
        now_time = datetime.datetime.now().strftime('%Y_%m_%d')
        log_file = os.path.join(log_dir, f"{now_time}.log")
        # 日志按天滚动,保留7天日志
        file_handler = handlers.TimedRotatingFileHandler(log_file,when='D',interval=1,encoding='utf-8',backupCount=7)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)

        if not logger.handlers:
            logger.addHandler(console)
            logger.addHandler(file_handler)


        return logger

log = Logger.getLogger("zm_log")


if __name__ == '__main__':
    log.info("hello world")
    log.debug("hello world")
    log.error("hello world")
